﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
using TaskStatus = TaskQueueDemo.ViewModel.TaskStatus;
namespace TaskQueueDemo.ViewModels
{
    public class TaskItem : INotifyPropertyChanged
    {
        private string _name;
        public string Name
        {
            get => _name;
            set { _name = value; OnPropertyChanged(); }
        }

        private TaskStatus _status;
        public TaskStatus Status
        {
            get => _status;
            set { _status = value; OnPropertyChanged(); }
        }

        private int _progress;
        public int Progress
        {
            get => _progress;
            set { _progress = value; OnPropertyChanged(); 
            PreProcess();
            }
        }
        private string _progressDesc;
        public string ProgressDesc
        {
            get => _progressDesc;
            set { _progressDesc = value; OnPropertyChanged(); }
        }

        public void PreProcess()
        {
            ProgressDesc = "进度啊" + Progress;
        }
        public void Process()
        {
            IProgress<int> progress = new Progress<int>(p => Progress = p);
            CancellationToken token = CancellationTokenSource.Token;
            for (int i = 0; i <= 100; i++)
            {
                token.ThrowIfCancellationRequested();
                System.Threading.Thread.Sleep(50);
                progress.Report(i);
            }
        }
        public Action TaskAction { get; set; }

        public CancellationTokenSource CancellationTokenSource { get; set; } = new CancellationTokenSource();

        public void Cancel()
        {
            CancellationTokenSource?.Cancel();
            Status = TaskStatus.Failed;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        public string CopyLogs()
        {
            return _name;
        }
    }
}